package com.imay.live.activity.dynamics;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.imay.base.helper.ActivityHelper;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.camera.CameraActivity2;
import com.imay.live.activity.camera.ClipActivity;
import com.imay.live.activity.video.RecordVideoActivity;
import com.imay.live.adapter.RepostAdapter;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.DymaicsUpdateHelper;
import com.imay.live.helper.MediaHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.manager.FamilyAccountManager;
import com.imay.live.model.FamilyApplyUserInfo;
import com.imay.live.model.FamilyModel;
import com.imay.live.model.FamilyUserInfo;
import com.imay.live.model.FeedModel;
import com.imay.live.model.FeedSuggestModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.AnimationUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.LoadView;
import com.imay.live.R;
import com.imay.live.view.dialog.ChoiseDialogFragment;

import java.util.ArrayList;
import java.util.List;


/**
 * 发布动态和转发动态的公共代码模块
 * Created by chan on 2017/4/17.
 */

public abstract class DynamicsFeedActivity extends BaseRequestActivity implements View.OnClickListener, ChoiseDialogFragment.OnItemClickListener {

    public static final int STATUS_RELEASE = 1;
    public static final int STATUS_REPOST = 2;

    public static final int MENU_ACTION_FEED_OPEN = 301; //公开
    public static final int MENU_ACTION_FEED_FAMILY = 302; //家族

    private MenuItemModel OPEN_MENU = new MenuItemModel(MENU_ACTION_FEED_OPEN, R.string.str_feed_menu_open, R.string.str_feed_menu_open_des);
    private MenuItemModel FAMILY_MENU = new MenuItemModel(MENU_ACTION_FEED_FAMILY, R.string.str_feed_menu_family, R.string.str_feed_menu_family_des);

    // 请求部分
    private String createFeedRequest;
    private String relationFollowsRequest;
    private String feedCreateRequest;
    private String feedModifyRequest;

    // 用户和话题
    protected List<UserModel> userModels = new ArrayList<>();
    protected List<FeedSuggestModel> labelModels = new ArrayList<>();

    protected ImageView mRightView;

    protected boolean isShow = false;
    protected boolean isShowing = false;

    protected ImageView mRepostAt, mRepostJin;
    protected RepostAdapter mAdapter;
    protected RecyclerView mRecyclerView;
    protected EditText mEtContent;
    protected TextView mCountText, tv_familyId_status;
    protected Context mContext;
    protected LoadView loadView;

    protected int count = 100;
    private int atFirstPosition = 0;
    private int jinFirstPosition = 0;

    protected boolean toaststatus = true;

    protected InputMethodManager imm;

    protected int internalPublic;
    protected int familyId = 0;
    protected int feedStauts;
    protected int beLocked;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mContext = this;
        UserInfoModel userInfo = UserInfoCache.getUserInfo();
        if (userInfo != null) {
            UserInfoModel.StatModel statModel = userInfo.getStat();
            createFeedRequest = ProtoRequestHelper.task(ProtoHttpFactory.labelCreateFeedSuggest()).setTag(this.hashCode()).request(this);
            relationFollowsRequest = ProtoRequestHelper.task(ProtoHttpFactory.relationFollows(0, statModel.getFollow())).setTag(this.hashCode()).request(this);
        }

        if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
            FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
            beLocked = familyUserInfo.getFamily().getBeLocked();
        }
    }

    protected void setRightView() {
        mRightView = new ImageView(this);
        mRightView.setImageResource(R.mipmap.btn_fasong);
        mRightView.setPadding(0, 0, 0, 0);
        getTitleBar().getRightView().addView(mRightView);
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        if (command.equals(relationFollowsRequest)) { // 关注列表
            Result<List<UserModel>> result = JSON.parseObject(data, new TypeReference<Result<List<UserModel>>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                if (result.data != null) {
                    userModels.addAll(result.data);
                }
            } else {
                ErrorResult.toastError(this, result.result);
            }
        } else if (command.equals(createFeedRequest)) {   // 话题
            Result<List<FeedSuggestModel>> result = JSON.parseObject(data, new TypeReference<Result<List<FeedSuggestModel>>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                if (result.data != null) {
                    labelModels.addAll(result.data);
                }
            } else {
                ErrorResult.toastError(this, result.result);
            }
        } else if (command.equals(feedCreateRequest)) {
            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            Result<FeedModel> result = JSON.parseObject(data, new TypeReference<Result<FeedModel>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                if (toaststatus) {
                    ToastUtil.showImg(this, getString(R.string.str_realse_send_sucess), R.mipmap.jiaohutishidagou_3x, 200);
                }
                /**
                 * 发布新的动态
                 */
                DymaicsUpdateHelper.createDynamics(result.data);
                setResult(RESULT_OK);
                MediaHelper.finishActivity();
                finish();
            } else {
                ToastUtil.showImg(this, ErrorResult.getString(this, result.result), R.mipmap.jiaohutishidaxia_3x, 200);
            }
        } else if (command.equals(feedModifyRequest)) {
            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
            Result<FeedModel> result = JSON.parseObject(data, new TypeReference<Result<FeedModel>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                ToastUtil.showImg(this, getString(R.string.str_modify_send_success), R.mipmap.jiaohutishidagou_3x, 200);
                /**
                 * 修改动态
                 */
                DymaicsUpdateHelper.modifyDynamics(result.data);
                setResult(RESULT_OK);
                finish();
            } else {
                ToastUtil.showImg(this, ErrorResult.getString(mContext, result.result), R.mipmap.jiaohutishidaxia_3x, 200);
            }
        }
    }

    @Override
    public void finish() {
        if (imm != null) {
            imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
        }
        super.finish();
    }

    /**
     * 公共的监听模块
     */
    protected void initListener() {
        mEtContent.addTextChangedListener(mTextWatcher);

        tv_familyId_status.setOnClickListener(this);
        mRepostAt.setOnClickListener(this);
        mRepostJin.setOnClickListener(this);

        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (imm != null) {
                    imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                }
                return false;
            }
        });

        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (imm != null) {
                    imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                }
                Object item = mAdapter.getItem(position);
                if (item instanceof UserModel) {
                    UserModel user = (UserModel) item;
                    String string = mEtContent.getText().toString() + getString(R.string.str_dynamics_at_text, user.getNick()) + " ";
                    if (string.length() > count) {
                        ToastUtil.show(mContext, R.string.str_dynamics_comment_note);
                        return;
                    }
                    mEtContent.setText(string);
                    mEtContent.setSelection(string.length());
                } else if (item instanceof FeedSuggestModel) {
                    FeedSuggestModel label = (FeedSuggestModel) item;
                    String string = mEtContent.getText().toString() + getString(R.string.str_dynamics_jin_text, label.getContent()) + " ";
                    if (string.length() > count) {
                        ToastUtil.show(mContext, R.string.str_dynamics_comment_note);
                        return;
                    }
                    mEtContent.setText(string);
                    mEtContent.setSelection(string.length());
                }
                if (imm != null) {
                    imm.showSoftInput(mEtContent, 0);
                }
            }
        });
    }

    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        ErrorResult.toastError(this, code);
    }

    /**
     * 创建动态
     *
     * @param imageUrl
     * @param videoUrl
     * @param msg
     * @param city
     * @param longitude
     * @param latitude
     * @param feedid
     */
    protected void createFeed(String imageUrl, String videoUrl, String msg, String city, String longitude, String latitude, int feedid, int familyId) {
        feedCreateRequest = ProtoRequestHelper.task(ProtoHttpFactory.feedCreate(imageUrl, videoUrl, msg, city, longitude, latitude, feedid, familyId)).setTag(this.hashCode()).request(this);
    }

    /**
     * 编辑动态
     *
     * @param feedId
     * @param msg
     */
    protected void modifyFeed(int feedId, String msg) {
        feedModifyRequest = ProtoRequestHelper.task(ProtoHttpFactory.feedModify(feedId, msg, familyId)).setTag(this.hashCode()).request(this);
    }

    /**
     * 监听动画
     */
    protected Animation.AnimationListener animationListener = new Animation.AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
            isShowing = true;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            isShowing = false;
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    };


    TextWatcher mTextWatcher = new TextWatcher() {
        private CharSequence temp;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            temp = s;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            if (isShow) {
                mRecyclerView.setVisibility(View.INVISIBLE);
                mRepostAt.setSelected(false);
                mRepostJin.setSelected(false);
                AnimationUtil.startToBottomAnimation(mRecyclerView, 500, animationListener);
                isShow = false;
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            mCountText.setText(Integer.toString(count - temp.length()));
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_repost_at: // @符号
                if (isShowing) {
                    return;
                }
                mRepostJin.setSelected(false);
                if (mRepostAt.isSelected()) {
                    loadView.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.INVISIBLE);
                    mRepostAt.setSelected(false);
                    if (isShow) {
                        AnimationUtil.startToBottomAnimation(mRecyclerView, 500, animationListener);
                        isShow = false;
                    }
                } else {
                    if (userModels.isEmpty()) {
                        loadView.setVisibility(View.VISIBLE);
                        loadView.loadError();
                    } else {
                        loadView.setVisibility(View.GONE);
                    }
                    mRepostAt.setSelected(true);
                    RecyclerView.LayoutManager manager = mRecyclerView.getLayoutManager();
                    if (manager instanceof LinearLayoutManager) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
                        jinFirstPosition = layoutManager.findFirstVisibleItemPosition() == -1 ? 0 : layoutManager.findFirstVisibleItemPosition();
                    }
                    mAdapter.setUserModels(userModels);
                    if (manager instanceof LinearLayoutManager) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
                        layoutManager.scrollToPositionWithOffset(atFirstPosition, 0);
                    }
                    mRecyclerView.setVisibility(View.VISIBLE);
                    if (!isShow) {
                        AnimationUtil.startFromBottomAnimation(mRecyclerView, 500, animationListener);
                        isShow = true;

                        if (imm != null) {
                            imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                        }
                    }
                }
                break;
            case R.id.iv_repost_jin: // #符号
                if (isShowing) {
                    return;
                }
                mRepostAt.setSelected(false);
                if (mRepostJin.isSelected()) {
                    loadView.setVisibility(View.GONE);
                    mRepostJin.setSelected(false);
                    mRecyclerView.setVisibility(View.INVISIBLE);
                    if (isShow) {
                        AnimationUtil.startToBottomAnimation(mRecyclerView, 500, animationListener);
                        isShow = false;
                    }
                } else {
                    mRepostJin.setSelected(true);
                    if (labelModels.isEmpty()) {
                        loadView.setVisibility(View.VISIBLE);
                        loadView.loadError();
                    } else {
                        loadView.setVisibility(View.GONE);
                    }
                    RecyclerView.LayoutManager manager = mRecyclerView.getLayoutManager();
                    if (manager instanceof LinearLayoutManager) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
                        atFirstPosition = layoutManager.findFirstVisibleItemPosition() == -1 ? 0 : layoutManager.findFirstVisibleItemPosition();
                    }
                    mAdapter.setLabelModels(labelModels);
                    if (manager instanceof LinearLayoutManager) {
                        LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
                        layoutManager.scrollToPositionWithOffset(jinFirstPosition, 0);
                    }
                    mRecyclerView.setVisibility(View.VISIBLE);
                    if (!isShow) {
                        AnimationUtil.startFromBottomAnimation(mRecyclerView, 500, animationListener);
                        isShow = true;
                        if (imm != null) {
                            imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                        }
                    }
                }
                break;
            case R.id.tv_repost_count:
            case R.id.tv_repost_des:
                if (imm != null) {
                    imm.showSoftInput(mEtContent, 0);
                }
                break;
            case R.id.tv_familyId_status:
                if (imm != null) {
                    imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                }
                final List<MenuItemModel> menu = new ArrayList<>();
                if (FamilyAccountManager.getInstance().isHasFamilyInfo()) {
                    if (feedStauts == STATUS_RELEASE) {
                        if (beLocked == 0) {
                            menu.add(OPEN_MENU);
                            menu.add(FAMILY_MENU);
                        } else if (beLocked == 1) {
                            menu.add(OPEN_MENU);
                        }
                    } else if (feedStauts == STATUS_REPOST) {
                        if (internalPublic == 0) {
                            if (beLocked == 0) {
                                menu.add(OPEN_MENU);
                                menu.add(FAMILY_MENU);
                            } else if (beLocked == 1) {
                                menu.add(OPEN_MENU);
                            }
                        } else {
                            if (beLocked == 0) {
                                menu.add(FAMILY_MENU);
                            } else if (beLocked == 1) {
                                break;
                            }
                        }
                    }
                } else {
                    menu.add(OPEN_MENU);
                }
                ThreadManager.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ChoiseDialogFragment.show(getSupportFragmentManager(), menu, this.hashCode(), DynamicsFeedActivity.this);
                    }
                }, 100);
                break;
        }
    }

    @Override
    public void itemClick(int tagCallBack, int position, MenuItemModel str) {
        switch (str.getAction()) {
            case MENU_ACTION_FEED_OPEN:
                familyId = 0;
                tv_familyId_status.setText(str.getTextId());
                break;
            case MENU_ACTION_FEED_FAMILY:
                FamilyUserInfo familyUserInfo = FamilyAccountManager.getInstance().getFamilyUserInfo();
                if (familyUserInfo != null) {
                    FamilyModel familyModel = familyUserInfo.getFamily();
                    if (familyModel != null) {
                        familyId = familyModel.getId();
                        tv_familyId_status.setText(str.getTextId());
                    }
                }
                break;
        }
    }
}
